import axios from 'axios'
import API from '../api'
import { showLoading, hideLoading } from './loading'
import { Message } from 'element-ui'
import { removeUser,getUserData } from '@/utils/loginauth.js'

const ResultCode = {
	CODE_FAIL: -1,
	CODE_SUCCESS: 0,
	CODE_NO_MODULE: 1000,
	CODE_INVALID_INPUT: 1001,
	CODE_SESSION_EXPIRED: -1002,
	CODE_PERMISSION_DENIED: 1003,
}
// let count = 0
export default {
	install(Vue) {
		let self = this

		// 在实例已创建后修改默认值
		// instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
		axios.defaults.withCredentials = true
		axios.defaults.timeout = 60000

		axios.interceptors.request.use(
			function(config) {
				const token = getUserData()
				let time = new Date().getTime() / 1000
				if (token) {
					config.headers.common['token'] = `${token.token}`
				}
				config.headers.common['time'] = `${time.toFixed(0)}`
				//根据vuex store内容动态设置baseurl
				//config.baseURL = store.getters.baseUrl;
				//config.url = `${baseUrl}/${config.url}`;
				if (config.method !== 'get') {
					if (config.showLoading) {
						showLoading()
					}
				}
				hideLoading()
				return config
			},
			function(error) {
				self.hintAWhile('[错误] 请求超时', 'error')
				return Promise.reject(error)
			}
		)
		//响应拦截
		// axios.interceptors.response.use(function (response) {
		
		// 	return response;
		// }, function (error) {
		
		// 	return Promise.reject(error);
		// });
		// 设置为Vue的全局属性
		Vue.http = this
		Vue.prototype.$http = this
		Vue.API = API
		Vue.prototype.$API = API
	},

	hintAWhile: function(msg, type) {
		Message({
			showClose: true,
			message: msg,
			center: true,
			duration: 3000,
			type: type ? type : 'info', // success/warning/info/error
		})
	},

	/**
	 * options ：同mopoPost
	 */
	handleResponse: function(options, resp) {
		let self = this
		let mess = resp.message
		switch (resp.code) {
			case ResultCode.CODE_SUCCESS:
				if (options.success) {
					options.success.call(self, resp)
				}
				break
			case ResultCode.CODE_INVALID_INPUT:
			case ResultCode.CODE_FAIL:
				if (options.error) {
					options.error.call(self, resp)
				} else if (resp.message) {
					self.hintAWhile('[错误] ' + resp.message, 'error')
				} else {
					self.hintAWhile(
						'[错误] ' + '服务器发生未知错误，请联系管理员！',
						'error'
					)
				}
				break
			case ResultCode.CODE_PERMISSION_DENIED:
				self.hintAWhile('[错误] ' + '对不起，您没有使用该功能的权限!', 'error')
				break
			case ResultCode.CODE_SESSION_EXPIRED:
				// setTimeout(window.location.href = '../shike3k-user/#/login?code='+ removeUser(),2000)
				// if (JSON.parse(window.sessionStorage.getItem('currentUser'))) {
				// 	count = 0
				// }
				// if (count < 1) {
				if (JSON.parse(window.sessionStorage.getItem('currentUser'))) {
					let partnershipCode = removeUser()
					window.location.href =
						'/shike3k/user/index.html#/login?code=' + partnershipCode
					if (document.getElementsByClassName('el-message').length < 2) {
						self.hintAWhile('[错误] ' + '会话已过期，请重新登录!', 'error')
					}
					setTimeout((
						location.reload())
				, 2000)
				
				
				} else {
					setTimeout((window.location.href = '/shike3k/user/index.html#/login'), 2000)
					// }
					// count = count + 1
				}
				break
			case ResultCode.CODE_NO_MODULE:
				self.hintAWhile('[错误] ' + '没有您要的资源，是不是迷路了？', 'error')
				break
			default:
		
			
				if(resp.code == -3 && resp.message.includes('您正在使用')){
					mess = resp.message.split("，")[0] + ",请关闭后再开启其他插座"

				}
				Message({
					showClose: true,
					message:mess,
					center: true,
					duration: 3000,
					type:'error', // success/warning/info/error
				})
				break
		}
	},

	get: function(options) {
		options.method = 'get'
		this.req(options)
	},

	post: function(options) {
		options.method = 'post'
		this.req(options)
	},
	/**
	 * options = {
	 * 		"url" : 	服务端地址，不包含BASE_URL
	 * 		"data":		提交的参数
	 * 	    "method":   提交方式，默认post, 可为get, put, patch, delete, head
	 * 		"jsonBody": true or false 指定是否用application/json提交数据
	 * 		"success" : 请求成功,服务端返回success后的回调
	 * 		"error" :   请求成功,服务端返回非success后的回调
	 */
	req: function(options) {
		if (typeof options.jsonBody === 'undefined') options.jsonBody = true
		let self = this
		let ct = options.jsonBody
			? 'application/json;charset:utf-8;'
			: 'application/x-www-form-urlencoded;charset:utf-8;'
		let d = options.jsonBody ? JSON.stringify(options.data) : options.data
		let loadingFlag
		if (typeof options.showLoading !== 'undefined') {
			loadingFlag = options.showLoading
		} else {
			loadingFlag = true
		}
		axios({
			url: options.url,
			method: options.method,
			data: d,
			withCredentials: true,
			headers: { 'Content-Type': ct },
			showLoading: loadingFlag,
		})
			.then(function(response) {
				hideLoading()
				self.handleResponse(options, response.data)
			})
			.catch(function(error) {
		
				hideLoading()
				if (error.response) {
					// 请求已发出，但服务器响应的状态码不在 2xx 范围内
					// console.log(error.response.data)
					// console.log(error.response.status)
					// console.log(error.response.headers)
					if (document.getElementsByClassName('el-message').length === 0) {
						self.hintAWhile('服务端响应错误!', 'error')
					}
				} else {
					// Something happened in setting up the request that triggered an Error
					console.log('Error', error.message)
					// self.hintAWhile(error.message, 'error')
				}
				console.log(error.config)
			})
	},
}
